package com.hunk.springMvcExercise.web.servlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Decoder;

import com.hunk.utils.JacksonUtil;

/** Description:<br>
 * Use Json For Transport Media In Request and Response
 * @see
 * 	Servlet implementation class JsonServlet
 * @author Hunk
 * @since 2013-4-3
 */
public class JsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JsonServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String result = "";
		try {
			/* 读取数据 */
			BufferedReader br = new BufferedReader(
					new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
			StringBuffer sb =new StringBuffer("");
			String temp;
			while((temp=br.readLine())!=null){
				sb.append(temp);
			}
			br.close();
			result = sb.toString();
			System.out.println("请求报文:" + result);
			
			Weibo wb = JacksonUtil.getBeanFromJson(result, Weibo.class);
			
			saveWb(wb);
		} catch (Exception e) {
			result = "{err:\"error\"}";
		} finally {
			/* 返回数据 */
			System.out.println("返回报文:" + result);
			BufferedWriter pw = new BufferedWriter(
					new OutputStreamWriter((ServletOutputStream) response.getOutputStream(), "utf-8"));
			pw.write(result);
			pw.flush();
			pw.close();
		}
	}

	final static String temp = "D:/temp/upload/";
	private void saveWb(Weibo wb) {
		String base64str = wb.getFile1();
		BASE64Decoder dec = new BASE64Decoder();  
		byte[] mybyte = null;
        try {  
        	mybyte = dec.decodeBuffer(base64str);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
		File file = new File(temp + getPhotoFileName());
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(mybyte);
	        out.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {			
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        
	}
	
	/** 用当前时间给取得的图片命名  */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyy-MM-dd-HH-mm-ss-SSSSSS");
//		System.out.println(dateFormat.format(date) + ".jpg");
		return dateFormat.format(date) + ".jpg";
	}
}

class Weibo {
	private String title;
	private String description;
	private String file1;
	private String file2;
		
	/**
	 * @author HunkDeng
	 * @return
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public String toJson() throws IllegalArgumentException, IllegalAccessException {
		StringBuffer sb = new StringBuffer();
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {			
			sb.append(field.getName() + ":" + field.get(this) + "  ");			
		}
		return sb.toString();
	}
	
	public Weibo() {
		super();
	}
	
	public Weibo(String title, String description, String file1, String file2) {
		super();
		this.title = title;
		this.description = description;
		this.file1 = file1;
		this.file2 = file2;
	}
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getFile1() {
		return file1;
	}
	public void setFile1(String file1) {
		this.file1 = file1;
	}
	public String getFile2() {
		return file2;
	}
	public void setFile2(String file2) {
		this.file2 = file2;
	}	
	@Override
	public String toString() {
		return "Weibo [title=" + title + ", description=" + description
				+ ", file1=" + file1 + ", file2=" + file2 + "]";
	}
}



